﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.IO;
using System.Net;
namespace OgilvyOne.PreorderWap
{

    public class PostAPI
    {
        public PostAPI()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }


        private static string urlEcode(string str)
        {
            Encoding myEncoding = Encoding.GetEncoding("utf-8");
            return HttpUtility.UrlEncode(str, myEncoding);
        }


        public string Save(string username, string sex, string mobile, string email, string buytime, string buybudget, string source, string Displacement, string CarModel, string CarColor, string CarSeat, string channel,string apiAddress)
        {

            //正式
            //string urlAddress = "http://vico1.vw.com.cn/newcms/testdrive/api/regsave.aspx";
            //测试
            //string urlAddress = "http://vico.ogilvy.com.cn/newcms/testdrive/api/regsave.aspx";
            string urlAddress = apiAddress;
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("camname", "wapbeetlepreorder");
            dic.Add("&id", "124");
            dic.Add("&username", username);
            dic.Add("&sex", sex);
            dic.Add("&mobile", mobile);
            dic.Add("&email", email);
            dic.Add("&buytime", buytime);
            dic.Add("&buybudget", buybudget);
            dic.Add("&isincept", "0");
            dic.Add("&Displacement", Displacement);
            dic.Add("&CarModel", CarModel);
            dic.Add("&CarColor", CarColor);
            dic.Add("&CarSeat", CarSeat);
            dic.Add("&source", source);
            dic.Add("&channel", channel);
            dic.Add("&dealerprovince", "");
            dic.Add("&dealercity", "");
            dic.Add("&dealer", "");

            return SendMessage(urlAddress, dic);
        }


        #region Post提交数据封装

        public string SendMessage(string endPoint, Dictionary<string, string> paramters)
        {
            string message = "";
            Encoding myEncoding = Encoding.GetEncoding("utf-8");
            var populatedEndPoint = CreateFormattedPostRequest(paramters);
            byte[] bytes = Encoding.UTF8.GetBytes(populatedEndPoint);
            System.GC.Collect();
            HttpWebRequest request = CreateWebRequest(endPoint, bytes.Length);

            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }
            System.Net.ServicePointManager.Expect100Continue = false;
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    message = String.Format("POST Failed.Received HTTP{0}", response.StatusCode);
                }

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (StreamReader sr = new StreamReader(response.GetResponseStream(), myEncoding))
                    {
                        // 返回结果

                        if (sr.ReadToEnd() == "1")
                        {
                            message = "success";
                        }
                        else
                        {
                            message = "提交失败，数据有误！";
                            //ScriptManager.RegisterClientScriptBlock(Page, GetType(), "Fail", "alert('提交失败，数据有误！'); location.href='index.html';", true);
                        }
                    }
                }


            }

            if (request != null)
            {
                request.Abort();
            }

            return message;
        }

        /// <summary>
        /// 获取webRequest
        /// </summary>
        /// <param name="endPoint"></param>
        /// <param name="contentLength"></param>
        /// <returns></returns>

        private HttpWebRequest CreateWebRequest(string endPoint, Int32 contentLength)
        {
            System.Net.ServicePointManager.Expect100Continue = false;
            var request = (HttpWebRequest)WebRequest.Create(endPoint);
            request.Method = "POST";
            request.ContentLength = contentLength;
            request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            request.KeepAlive = false;
            request.Timeout = 100000;
            request.Proxy = null;
            System.Net.ServicePointManager.DefaultConnectionLimit = 50;
            return request;
        }

        /// <summary>
        /// 返回提交参数值
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        private string CreateFormattedPostRequest(Dictionary<string, string> values)
        {
            var paramterBuilder = new StringBuilder();
            var counter = 0;
            foreach (var value in values)
            {

                paramterBuilder.AppendFormat("{0}={1}", value.Key, HttpUtility.UrlEncode(value.Value));

            }
            counter++;

            return paramterBuilder.ToString();
        }

        #endregion
    }
}
